/*
 * Copyright 2005 Shinya Kasatani
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

if (!XMLHttpRequest.prototype.sendAsBinary) {
  XMLHttpRequest.prototype.sendAsBinary = function(sData) {
    var nBytes = sData.length, ui8Data = new Uint8Array(nBytes);
    for (var nIdx = 0; nIdx < nBytes; nIdx++) {
      ui8Data[nIdx] = sData.charCodeAt(nIdx) & 0xff;
    }
    /* send as ArrayBufferView...: */
    this.send(ui8Data);
    /* ...or as ArrayBuffer (legacy)...: this.send(ui8Data.buffer); */
  };
}

// shortcut
this.Preferences = SeleniumIDE.Preferences;

/*
 * A model that represents the state of the application.
 */
function OracleTcs(editor) {
    this.baseURL = "";
    this.options = editor.app.options;
    this.pluginManager = new PluginManager(this.options);
    this.baseURLHistory = new StoredHistory("baseURLHistory", 20);
    this.testCase = null;
    this.testSuite = null;
    this.currentTargetLang='en';
    this.currentProjectId=-1;
    this.editor=editor;
    this.case=null;
    this.text="";
    this.defTmpFolder=Components.classes["@mozilla.org/file/directory_service;1"].  
                     getService(Components.interfaces.nsIProperties).  
                     get("Desk", Components.interfaces.nsIFile).path
}

OracleTcs.prototype = {
    setBaseURL: function(baseURL) {
        this.baseURL = baseURL;
        this.notify("baseURLChanged");
    },
    setCase:function(testcase){
    	this.testCase = testcase;
    },
    addOngoingDIV : function() {
    	gb=editor.window.opener.getBrowser();
		doc = gb.selectedBrowser.contentDocument;

		var ni = doc.createElement('div');
		ni.id = "ssceOngoing";
		// var newtext = doc.createTextNode(txt);
		ni.innerHTML = "saving testcase and uploading, please wait";

		var _sL, _sT, _cH, _cW;
		if (doc.compatMode == "CSS1Compat") {
			_sL = doc.documentElement.scrollLeft;
			_sT = doc.documentElement.scrollTop;
			_cW = doc.documentElement.clientWidth;
			_cH = doc.documentElement.clientHeight;

		} else {
			_sL = doc.body.scrollLeft;
			_sT = doc.body.scrollTop;
			_cW = doc.body.clientWidth;
			_cH = doc.body.clientHeight;
		}

		with (ni.style) {
			width = '300px';
			height = '80px';
			color = 'blue';
			fontSize = '20px';
			backgroundColor = 'yellow';
			display = 'block';
			paddingTop = '15px';
			textAlign = 'center';
			left = parseInt(_cW - 200) / 2 + _sL + "px";
			top = parseInt(_cH - 50) / 2 + _sT + "px";
			position = 'absolute';
			zIndex = 1001;
		}
		doc.body.appendChild(ni);
		// ni.appendChild(newtext);

		// the top div to prevent user operate on the document
		var _tdiv = doc.createElement('div');
		_tdiv.id = "PreventOpration123we3";
		with (_tdiv.style) {
			width = '100%';
			height = '100%';
			display = 'block';
			left = '0px';
			top = '0px';
			position = 'absolute';
			zIndex = 5500;
		}
		doc.body.appendChild(_tdiv);

		setTimeout(function() {
			changeOngoingDIVColor();
		}, 500);

	},
    getCurrentDatetime: function (a) {
	  function b(a) {
		return a < 10 ? "0" + a : a
 	  }
	return (a.getFullYear() + b(a.getMonth() + 1) + b(a.getDate())
	+ b(a.getHours()) + b(a.getMinutes()) + b(a.getSeconds())).replace(/ /g, "")
    },

    sync: function(format){
    	if (arguments.length == 0)
    	  format=window.editor.app.getFormats().selectFormat('webdrivertestngformatter');
    	
       this.addOngoingDIV();

	   //_file=this.getCurrentDatetime(new Date())+".java";
	   _file="Testsomething.java";
   	   this.editor.syncTestCaseWithFormat1(format);
   	   //get exported case script, not really saving in temp location
   	    _content=format.saveAsNew1(this.testCase,this);
  
   	   var xmlhttp = new XMLHttpRequest();
       
       var url = this.options.tcsUploadServer;
       
       xmlhttp.onreadystatechange = function() {
         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var myArr = JSON.parse(xmlhttp.responseText);

            //alert('Sync finish');
            removeOngoingDIV();
            var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService();
            var windowManagerInterface = windowManager.QueryInterface(Components.interfaces.nsIWindowMediator);
            var topWindow = windowManagerInterface.getMostRecentWindow('global:selenium-ide');

            if (topWindow)
            {
        	   topWindow.close();
             }
         }
       };
    
       segments=[];
       //+ editor.app.options['currentProjectId']
       segments.push("Content-Disposition: form-data; name=\"pid\"\r\n\r\n" + "99\r\n");
       segments.push("Content-Disposition: form-data; name=\"folder\"\r\n\r\n"+ editor.app.options['tcsScriptLocation'] + "\r\n");
       segments.push("Content-Disposition: form-data; name=\"file[]\"; filename=\""+ _file + "\"\r\n\r\n");
       segments[2] += this.text + "\r\n";
       
       xmlhttp.open("POST", url, true);
       sBoundary = "---------------------------" + Date.now().toString(16);
       xmlhttp.setRequestHeader("Content-Type","multipart/form-data; boundary=" + sBoundary);
       xmlhttp.sendAsBinary("--" + sBoundary + "\r\n" + segments.join("--" + sBoundary + "\r\n") + "--" + sBoundary + "--\r\n");
       
   }
};

OracleTcs.prototype.log = Tcs.log = new Log("OracleTcs");
observable(OracleTcs);
